﻿using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using CSLauncher.Configuration.Interface;

namespace CSLauncher.Configuration.Xml
{
    internal class XmlConfiguration : ICSLauncherConfig
    {
        private readonly XmlDocument xml;
        public ISubmenu MainMenu { get; private set; }
        public int Version { get; private set; }

        private static readonly string directory;
        public static string Default { get; private set; }

        static XmlConfiguration()
        {
            string userFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            directory = Path.Combine(userFolder, "CSLauncher");
            Default = Path.Combine(directory, "Menu.config");
        }

        public static XmlConfiguration GetDefault()
        {
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            if (!File.Exists(Default))
            {
                File.WriteAllText(Default, Properties.Resources.DefaultConfig);
            }

            return new XmlConfiguration(Default);
        }

        public XmlConfiguration(string fileName)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(XmlSchema.Read(Assembly.GetExecutingAssembly().GetManifestResourceStream("CSLauncher.ConfigurationSchema.xsd"), 
                delegate { }));
            settings.ValidationType = ValidationType.Schema;

            using (XmlReader reader = XmlReader.Create(fileName, settings))
            {
                xml = new XmlDocument();
                xml.Load(reader);
            }

            MainMenu = new SubMenu(xml.DocumentElement.FirstChild, null);
            Version = Convert.ToInt32(xml.DocumentElement.Attributes["version"].Value);
        }
    }
}
